package com.pignest.hotel.ui.reception;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Booking;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.LivingCustom;
import com.pignest.hotel.beans.LivingSpecifics;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.ProtocolPrice;
import com.pignest.hotel.beans.ProtocolUnit;
import com.pignest.hotel.beans.Room;
import com.pignest.hotel.beans.TbAccounts;
import com.pignest.hotel.definition.InComeItemType;
import com.pignest.hotel.definition.LivingState;
import com.pignest.hotel.definition.LivingType;
import com.pignest.hotel.definition.OpenRoomType;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.definition.RoomLiveStatus;
import com.pignest.hotel.service.CardService;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Global;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class LivingWindow extends Window implements EventListener {
	private static final long serialVersionUID = 8535960359799405289L;
	
	private ReceptionService receptionService;
	private MemberService memberService;
	private CardService cardService;
	private Room room;
	private boolean success;
	private String msg;
	private Member member;
	private String bookingId;
	
	private Textbox roomNameTextbox;			//房间名
	private Listbox livingTypeListbox;
	private Textbox relativeRoomTextbox;		//关联的房间号, 团队, 联房
	private Textbox customNameTextbox;//客户姓名
	private Listbox sexListbox;//性别
	private Textbox phoneTextbox;
	//private Textbox otherContactTextbox;
	private Listbox passportTypeListbox;
	private Textbox passportNunberTextbox;
	//private Textbox cooperationUnitTextbox;
	private Textbox roomPrice;
	private Textbox pay;
	private Textbox adjustPrice;
	private Datebox leaveDate;
	private Listbox leaveTime;
	
	private Listbox paymentMethodListbox;
	private Listbox openRoomType;
	private Label roomType;
	private Textbox cardNumberTextbox;
	private Textbox remarkTextbox;
	
	private Listbox memberListbox;
	private Textbox nameQtext;
	private Textbox mobileQtext;
	private Textbox cardNoQtext;
	
	private Checkbox bookingCheckbox;
	

	private Listbox protocolUnitList;
    private Label protocolPrice;
    
	////会员信息////
	private Label memberLevel;
	private Label name;
	private Checkbox autoMasterCustom;
    private Label curBanlance;//当前余额
    private Label curIntegal;//当前积分
//    private Label curCredit;//当前信用
    private Living curLiving;
    private ProtocolUnit protocolUnit;
	
	public LivingWindow() {
		receptionService = Services.getReceptionService();
		memberService =Services.getMemberService();
		cardService =Services.getCardService();
		addEventListener("onCreate", this);
	}

	@Override
	public void onEvent(Event event) throws Exception {
		if ("onCreate".equals(event.getName())) {
			roomNameTextbox = (Textbox) getFellow("roomName");
			livingTypeListbox = (Listbox) getFellow("livingType");
			relativeRoomTextbox = (Textbox) getFellow("relativeRoom");
			customNameTextbox = (Textbox) getFellow("customName");
			sexListbox = (Listbox) getFellow("gender");
			phoneTextbox = (Textbox) getFellow("phone");
			//otherContactTextbox = (Textbox) getFellow("otherContact");
			passportTypeListbox = (Listbox) getFellow("passportType");
			passportNunberTextbox = (Textbox) getFellow("passportNumber");
			//cooperationUnitTextbox = (Textbox) getFellow("cooperationUnit");
			roomPrice = (Textbox) getFellow("roomPrice");
			adjustPrice = (Textbox) getFellow("adjustPrice");
			leaveDate = (Datebox) getFellow("leaveDate");
			leaveTime = (Listbox) getFellow("leaveTime");
			pay = (Textbox) getFellow("pay");
			paymentMethodListbox = (Listbox) getFellow("paymentMethod");
			cardNumberTextbox = (Textbox) getFellow("cardNumber");
			remarkTextbox = (Textbox)getFellow("remark");
			openRoomType =(Listbox)getFellow("openRoomType");
			memberListbox =(Listbox)getFellow("memberListbox");
			nameQtext=(Textbox)getFellow("nameQtext");
			mobileQtext=(Textbox)getFellow("mobileQtext");
			cardNoQtext=(Textbox)getFellow("cardNoQtext");
			
			bookingCheckbox = (Checkbox) getFellow("currentBooking");
			protocolUnitList=(Listbox)getFellow("protocolUnitList");
			protocolPrice=(Label)getFellow("protocolPrice");
			autoMasterCustom=(Checkbox)getFellow("autoMasterCustom");
			name=(Label)getFellow("name");
			memberLevel=(Label)getFellow("memberLevel");
			curBanlance =(Label)getFellow("curBanlance");
			roomType =(Label)getFellow("roomType");
			curIntegal =(Label)getFellow("curIntegal");
//			curCredit =(Label)getFellow("curCredit");
			//初始化非会员时的房间价格
			adjustPrice.setValue(Utils.toPrice(room.getType().getPrice()));
			roomNameTextbox.setValue(room.getName());
			roomType.setValue(room.getType().getName());
			leaveDate.setValue(new Date(System.currentTimeMillis() + DateUtil.ONE_DAY));
			
			roomPrice.setValue(Utils.toPrice(room.getType().getPrice()));
			//queryMember();
			initBooking();
		}
	}
	
	private void initBooking() {
		final Booking booking = Services.getReceptionService().getBooking(room);
		if (booking == null) {
			return;
		}
		final Checkbox currentBooking = bookingCheckbox;
		currentBooking.setChecked(true);
		currentBooking.setDisabled(false);
		currentBooking.setLabel(booking.getName() + " - " + booking.getPhone());
		setBooking(booking, false);
		currentBooking.addEventListener(Events.ON_CHECK, new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				setBooking(booking, !currentBooking.isChecked());
			}
		});
	}
	
	private void setBooking(Booking booking, boolean clear) {
		if (clear) {
			if (booking != null) {
				if (customNameTextbox.getValue().equals(booking.getName()))
					customNameTextbox.setValue(null);
				if (phoneTextbox.getValue().equals(booking.getPhone()))
					phoneTextbox.setValue(null);
				if (booking.getMember() != null) {
					clearSelectMember();
				}
			} else {
				customNameTextbox.setValue(null);
				phoneTextbox.setValue(null);
				clearSelectMember();
			}
			bookingId = null;
		} else {
			customNameTextbox.setValue(booking.getName());
			if (booking.getMember() != null) {
				setMember(booking.getMember());
				setSelectMember();
			}
			if (StringUtils.isNotEmpty(booking.getPhone())) {
				phoneTextbox.setValue(booking.getPhone());
			}
			bookingId = booking.getId();
		}
	}
	
	public void setRoom(Room room) {
		this.room = room;
	}
	
	public String check() {
		if (StringUtils.isBlank(customNameTextbox.getValue())) {
			return "请填写主客姓名. 带(*)标记的为必填项";
		}
		if (StringUtils.isBlank(passportNunberTextbox.getValue())) {
			return "请填写证件号码. 带(*)标记的为必填项";
		}
		if (StringUtils.isBlank(cardNumberTextbox.getValue())&&this.member!=null) {
			return "请先授权";
		}
		LivingType type = UIUtils.getSelectedValue(livingTypeListbox);
		PayMethod payMethod=(PayMethod)UIUtils.getSelectedValue(paymentMethodListbox);
		int adjustPriceCent = Utils.toPrice(adjustPrice.getValue());
		int payCent = Utils.toPrice(pay.getValue());
		if(!Utils.checkPrice(adjustPrice.getValue())||!Utils.checkPrice(pay.getValue()))
        {
       	 return "调整价与押金不合法：非负正数!";
        }
		if (type.isFree()) {
			if (adjustPriceCent != 0 || payCent != 0)
				return "免费和自用 的房价和押金需为0";
		} else {
			if(this.member!=null)//是会员
			{
				if(!payMethod.name().equals(PayMethod.MEMBER_CARD.name())){
					if(payCent<=0)
						return "收款方式不是会员卡：押金必填写!";
				}
			}else{
				if (adjustPriceCent < 0 || payCent < 0) {
					return "请填写调整价和押金.";
				}
			}
		}
		if (type == LivingType.TEAM) {
			String relativeRoom = relativeRoomTextbox.getValue();
			if (StringUtils.isNotBlank(relativeRoom)) {
				Room room = Services.getRoomService().getRoom(relativeRoom);
				if (room == null)
					return "所选择的关联房间不存在.";
				if (receptionService.getLiving(room) == null)
					return "选择的房间暂无人入住, 无法关联";
			}
		}
		Date d = leaveDate.getValue();
		String time = UIUtils.getSelectedValue(leaveTime);
		d = DateUtil.parseDate(d, time);
		if (d.getTime() < System.currentTimeMillis() + DateUtil.ONE_HOUR) {
			return "预离时间填写不正确";
		}
		return null;
	}
	  boolean checkPrice(String type,LivingType type2)
	  {
	  	int minPrice =room.getType().getMinPrice();
	  	int minHourPrice =room.getType().getMinHourPrice();
	  	int iAdjustPrice=Utils.toPrice(adjustPrice.getValue());;
	  	int minHalfDayPrice=room.getType().getMinHalfDayPrice();
	  	if(!type2.isFree()){
		  	if(type.equals(OpenRoomType.DAY.name())){
		  		if(iAdjustPrice<minPrice){
		  		 	UIUtils.alert("天房不能小于最低价:"+Utils.toPrice(minPrice));
		  		 	return false;
		  		}
		  	}else if(type.equals(OpenRoomType.HOURS.name())){
		  		
		  		if(iAdjustPrice<minHourPrice){
		  		 	UIUtils.alert("钟点房不能小于最低价:"+Utils.toPrice(minHourPrice));
		  		 	return false;
		  		}
		  	}else{
		  		if(iAdjustPrice<minHalfDayPrice){
		  		 	UIUtils.alert("半天房不能小于最低价:"+Utils.toPrice(minHourPrice/2));
		  		 	return false;
		  		}
		  	}
	  	}
	  	return true;
	  }
	public String grantCard(String cardSnr ,String roomLockNumber) {
		Card card =cardService.getCardBySerialNumber(cardSnr);
		if(card==null)
			return "卡在系统中不存在，请确认卡！"+cardSnr;
		//如果是用门卡 不用判断归属,如果是会员卡则要判断归属，不是当前登记的会员不能用会员卡作为门卡
		
		if(card.getType()==Card.TYPE_MEMBER){
			if(member!=null){
				if(!card.getCardNumber().equals(member.getCardNo())){
					return "抱歉！与登记的会员卡不一致，不能作为门卡!如果没有请用普通卡!";
				}
			}else{//使用会员卡，但又不登记会员
				return "本次入住没有登记该会员卡，请用普通卡!";
			}
		}
		Date d = DateUtil.parseDate(leaveDate.getValue(), (String)UIUtils.getSelectedValue(leaveTime));
		//设置卡
		card.setLockNumber(roomLockNumber);
		card.setLastUpdateTime(new Date());
		card.setExpireTime(d);
		receptionService.update(card);
		return null;
	}
	
	public String onSave() {
		try{
			success = false;
			if(!Hotel.onDuty()){
				return "当前操作人未值班不能操作！";
			}
			
			String error = check();
			if (error != null) {
				success = false;
				return error;
			}
			OpenRoomType oType =UIUtils.getSelectedValue(openRoomType);
			LivingType type = UIUtils.getSelectedValue(livingTypeListbox);
			if(!checkPrice(oType.name(),type)){
				return "价格限制!";
			}
			Living l = new Living();
			l.setRoom(room);
			
			
			if (type == LivingType.TEAM) {
				String relativeRoom = relativeRoomTextbox.getValue();
				Room room = Services.getRoomService().getRoom(relativeRoom);
				if (room != null) {
					Living living = receptionService.getLiving(room);
					if (living != null)
						l.setSerialNumber(living.getSerialNumber());
				}
			}
			if (l.getSerialNumber() == null)
				l.setSerialNumber(Global.getLivineSerialNumber());
			if(this.member!=null){
		 	 l.setMember(this.member);
			}
			String sGender =(String)UIUtils.getSelectedValue(sexListbox);
			String sCustomName=customNameTextbox.getValue();
			String sPhone =phoneTextbox.getValue();
			String sPassportType =(String)UIUtils.getSelectedValue(passportTypeListbox);
			String sPassportNumber =passportNunberTextbox.getValue();
			String remark =remarkTextbox.getValue();
			PayMethod payMethod=(PayMethod)UIUtils.getSelectedValue(paymentMethodListbox);
			int roomPriceCent=Utils.toPrice(roomPrice.getValue());
			int adjustPriceCent =Utils.toPrice(adjustPrice.getValue());
			int payCent =Utils.toPrice(pay.getValue());
			l.setLiveTime(new Date());
			l.setLiveState(LivingState.LIVING.name());
			l.setLiveType(type.name());
			l.setCustormName(sCustomName);
			l.setSex(sGender);
			l.setPhone(sPhone);
			l.setPassportType(sPassportType);
			l.setPassportNumber(sPassportNumber);
			l.setRoomPrice(roomPriceCent);
			l.setAdjustPrice(adjustPriceCent);
			l.setSelfHelp(false);
			l.setStorage(payCent);
			l.setAvailable(l.getStorage());
			l.setUsed(0);
			l.setCardNumber(cardNumberTextbox.getValue());
			Date d = DateUtil.parseDate(leaveDate.getValue(), (String)UIUtils.getSelectedValue(leaveTime));
			l.setGrantDate(d);
			l.setExpectLeaveDate(d);
			l.setRemark(remark);
			l.setOpenRoomType(oType.name());
			
			//l.setCooperationUnit(cooperationUnitTextbox.getValue());
			
			LivingSpecifics spec = l.renderSpecifics();
		
			
			if(payMethod.name().equals(PayMethod.MEMBER_CARD.name()))//用会员卡来支付
			{
			    if(this.member==null)
			    {
			    	return "非会员不能用会员卡支付押金";
			    }
				int exceed=memberService.exceedBalance(member, payCent, true);
				if(exceed<=0)
				{
					return "对不起，当前会员透支额度不够！"+Utils.toPrice(exceed);
				}
				
			}
			spec.setPaymentMethod(payMethod.name());
			/**初始设置账*/
			
				TbAccounts accounts=new TbAccounts();
				accounts.setLiving(l);
				//accounts.setType("押金");
				accounts.setType(InComeItemType.YJ.name());
				
				accounts.setPrice(payCent);
				accounts.setCounts(1);
				accounts.setEndstate("否");
				//accounts.setName("押金");
				accounts.setName(InComeItemType.YJ.getValue());
				accounts.setOptime(new Date());
				accounts.setPrice2(payCent);
				accounts.setOpUser(Hotel.getCurrentUser().getName());
				accounts.setOpdate(DateUtil.currentDateToString(DateUtil.DEFAULT_DATE_FORMAT));
				accounts.setRemark(DateUtil.currentDateToString(DateUtil.DEFAULT_DATE_FORMAT)+"押金:"+Utils.toPrice(payCent));
			
				/***设置主要客人**/
				LivingCustom lc = new LivingCustom();
				lc.setLiving(l);
				lc.setName(sCustomName);
				lc.setIshost("是");
				lc.setCertificatetype(sPassportType);
				lc.setCertificateno(sPassportNumber);
				lc.setPhone(sPhone);
				lc.setSex(sGender);
				//receptionService.insert(lc);
				String respectfully=l.getRespectfully();
			room.setLiveStatus(RoomLiveStatus.FILLED.name());

			//暂时先在会员帐上扣，但不记充值明细记录中
			/*if(payMethod.name().equals(PayMethod.MEMBER_CARD.name())){
				int mb =member.getBalance();
				member.setBalance(mb-pay*100);
			}*/
			StringBuffer msg = new StringBuffer();	
			msg.append("欢迎你：").append(sCustomName).append(respectfully).append("\n");
			
			msg.append("房间号：").append(room.getName()).append("\n");
			msg.append("房间类型："+room.getType().getName()).append("\n");
			msg.append("开房方式:").append(oType.getDisplayName()).append("\n");
			msg.append("支付方式："+payMethod.getDisplayName()+"\n");
			msg.append("授权时间：").append(DateUtil.toString(d)).append("\n");
			msg.append("押金：").append(Utils.toPrice(payCent)).append("\n");
            msg.append("房价：").append(Utils.toPrice(roomPriceCent)).append("\n");
            if(this.member!=null){
				msg.append("会员").append("\n");
				msg.append("会员价:").append(Utils.toPrice(adjustPriceCent)).append("\n");
            }
			else if(this.protocolUnit!=null){
				l.setProtocolUnit(this.protocolUnit);
				msg.append("非会员").append("\n");
				msg.append("协议价:").append(Utils.toPrice(adjustPriceCent));
			}else
			{
				msg.append("非会员").append("\n");
				msg.append("入住价:").append(Utils.toPrice(adjustPriceCent));
			}
			if (UIUtils.confirm(msg.toString())) {
				receptionService.updateSingleRoomLiving(l, spec, room, accounts, member, lc, null, bookingId);
				success = true;
				this.setCurLiving(l);
				return null;
			} else {
				success = false;
				return "取消入住";
			}
		} catch (Exception e) {
			success = false;
			return e.getMessage();
		}
		
	}
    public void queryMember(){
    	memberListbox.getItems().clear();
    	String sName=nameQtext.getValue();
    	String sMobile=mobileQtext.getValue();
    	String sCardNo=cardNoQtext.getValue();
    	List<Member> mList =memberService.query(sName, sMobile, null, null, null, sCardNo);
    	for(final Member m:mList){
    		Listitem listitem = new Listitem();
			listitem.setParent(memberListbox);
			listitem.appendChild(new Listcell(m.getName()));//姓名
			listitem.appendChild(new Listcell(m.getCardNo()));//手机
//			listitem.appendChild(new Listcell(MoneyUtil.toString(m.getBalance())));
			listitem.addEventListener(Events.ON_CLICK,  new EventListener(){
				public void onEvent(Event event) throws Exception { 
					setMember(m);
					setSelectMember();
				}
			});
    	}
    }
	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public boolean isSuccess() {
		return success;
	}
	
	public void setSelectMember() {
		if(this.member!=null){
			name.setValue(member.getName());
			memberLevel.setValue(member.getMemberLevel().getMemberlevel());
			curBanlance.setValue(MoneyUtil.toString(member.getBalance()));
			Integer ral = member.getIntegral();
			if(ral!=null)
			   curIntegal.setValue(String.valueOf(ral));
//			Integer credit =member.getCredit();
//			if(credit!=null)
//				curCredit.setValue(String.valueOf(credit));
			cardNumberTextbox.setValue(member.getCardNo());
			//会员价
			int mPrice =memberService.getMemberPrice(member.getId(), room.getType().getId());
		     adjustPrice.setValue(Utils.toPrice(mPrice));
			if(autoMasterCustom.isChecked()){
				customNameTextbox.setValue(member.getName());
				phoneTextbox.setValue(member.getMobile());
			     UIUtils.setSelectedItem(sexListbox,member.getSex());
			     UIUtils.setSelectedItem(passportTypeListbox,member.getCertificatType());
			     passportNunberTextbox.setValue(member.getCertificateNo());
			     
			}
		}
		 
	}
	//清空页面选择的会员
	public void clearSelectMember(){    
		memberLevel.setValue("");
		name.setValue("");
		customNameTextbox.setValue("");
		phoneTextbox.setValue("");
		passportTypeListbox.setSelectedIndex(0);
		passportNunberTextbox.setValue("");
		cardNumberTextbox.setValue("");
		curBanlance.setValue("");
		curIntegal.setValue("");
//		curCredit.setValue("");
		adjustPrice.setValue(Utils.toPrice(room.getType().getPrice()));
		this.member=null;
	}
	public void isNoCustom(boolean is){

		if(is&&this.member!=null){
			customNameTextbox.setValue(member.getName());
			phoneTextbox.setValue(member.getMobile());
	        UIUtils.setSelectedItem(sexListbox,member.getSex());
	        UIUtils.setSelectedItem(passportTypeListbox,member.getCertificatType());
	        passportNunberTextbox.setValue(member.getCertificateNo());
	        
		}else{
			customNameTextbox.setValue("");
			phoneTextbox.setValue("");
			passportTypeListbox.setSelectedIndex(0);
			passportNunberTextbox.setValue("");

		}
	}
	  public void queryProtocolUnit(String unitName,String conName){
			protocolUnitList.getItems().clear();
			List<ProtocolUnit> list =Services.getOtherBusiService().queryProtocolUnit(null, unitName, conName,true);
			if(list==null)
				return ;
			for(final ProtocolUnit u:list)
			{
				Listitem listitem = new Listitem();
				listitem.setValue(u.getId());
				listitem.setParent(protocolUnitList);
				listitem.appendChild(new Listcell(u.getCompany()));
				listitem.appendChild(new Listcell(u.getContactName()));
				listitem.addEventListener(Events.ON_CLICK, new EventListener() {
					
					@Override
					public void onEvent(Event event) throws Exception {
						// TODO Auto-generated method stub
						queryProtocolPrice(u.getId());
						setProtocolUnit(u);
					}
				});
			}
		}
	  public void queryProtocolPrice(String protocolId){

		  ProtocolPrice p =Services.getOtherBusiService().queryProtocolPrice(protocolId,room.getType().getId());
		  if(p==null)
			  return ;
		  protocolPrice.setValue(Utils.toPrice(p.getPrice()));
		  adjustPrice.setValue(Utils.toPrice(p.getPrice()));
		  
		 
	  }
	  


	public ProtocolUnit getProtocolUnit() {
		return protocolUnit;
	}

	public void setProtocolUnit(ProtocolUnit protocolUnit) {
		this.protocolUnit = protocolUnit;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Room getRoom() {
		return room;
	}

	public Living getCurLiving() {
		return curLiving;
	}

	public void setCurLiving(Living curLiving) {
		this.curLiving = curLiving;
	}
	
}
